import parser from 'url-parse';

/**
 * 将url利用url-parse工具转换成url对象 
 * @param {String} url 待转换的url
 */
export const parse = (url) => {
    const parsed = parser(url);
    if(parsed.query.length > 0) {
        const qString = parsed.query.slice(1);
        const pairArray = qString.split('&');
        const query = {};
        pairArray.forEach((value) => {
            const node = value.split('=');
            query[node[0]] = node[1];
        });
        parsed.query = query;
    }
    return parsed;
}

/**
 * 将字面量对象转化为查询字符串的形式
 * @param {Object} obj 待转换的对象
 */
export const objectToQueryString = (obj) => {
    if(obj) {
        const queryArray = Object.keys(obj).map(key => `${key}=${obj[key]}`);
        return `?${queryArray.join('&')}`;
    } else { return ``; }
}